//
//  SinaPublishViewController.swift
//  WeiBo01
//
//  Created by mac on 16/1/9.
//  Copyright © 2016年 Han. All rights reserved.
//

import UIKit

class SinaPublishViewController: UIViewController, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        //改变背景颜色
        self.view.backgroundColor = UIColor.whiteColor()
        // Do any additional setup after loading the view.
        
        setupNav()
        
        setupTextView()
        
        setupToolBar()
        
        //监听键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    func changeFrame(noti: NSNotification){
        
        let rect = noti.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue
        let duration = noti.userInfo![UIKeyboardAnimationDurationUserInfoKey]?.doubleValue
        //toolbar向上的偏移
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-(kUIScreenHeight - rect!.origin.y))
        }
        
        //添加一个动画
        UIView.animateWithDuration(duration!) { () -> Void in
            //刷新toolBar的约束
            self.toolBar.layoutIfNeeded()
        }
        
    }
    
    //添加通知后要移除
    deinit{
        
//        removeObserver(self, forKeyPath: UIKeyboardDidChangeFrameNotification)
    }
    
    //MARK:--懒加载
    /// textView
    lazy var textView: SinaTextView = SinaTextView ()
    
    ///底部toolBar
    lazy var toolBar: UIToolbar = UIToolbar()
    
    ///选择图片
    lazy var chooseView: SinaChooseView = SinaChooseView()
    
}

//MARK:--设置toolBar
extension SinaPublishViewController{
    
    private func setupToolBar(){
        
        view.addSubview(toolBar)
        
        toolBar.backgroundColor = UIColor.darkGrayColor()
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(44)
        }
        
        //添加item
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        //定义一个数组来接收item
        var items: [UIBarButtonItem] = [UIBarButtonItem]()
        //遍历
        for item in itemSettings {
            
            //自定义item
            let button = UIButton(type: UIButtonType.Custom)
            let imageName = item["imageName"]
            
            button.setImage(UIImage(named: imageName!), forState: UIControlState.Normal)
            button.setImage(UIImage(named: "\(imageName)_highlighted"), forState: UIControlState.Highlighted)
            
            //如果有按钮方法,添加上按钮方法
            if let action = item["action"]{
                
                button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            }
            
            button.sizeToFit()
            //添加button
            items.append(UIBarButtonItem(customView: button))
            //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        
        toolBar.items = items
        
    }
    
    func choosePicture(){
        printLog("选取图片")
        
        let picture = UIImagePickerController()
        
        //用之前检测一下
        if UIImagePickerController.isSourceTypeAvailable( UIImagePickerControllerSourceType.PhotoLibrary) {
            
            picture.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            
            presentViewController(picture, animated: true, completion: { () -> Void in
                
            })
            
            //设置代理
            picture.delegate = self
        }
    }
    
    func inputEmoticon(){
        printLog("添加表情")
    }
    
}

//MARK:--图片选择的代理方法
extension SinaPublishViewController {
    
    //点击取消的时候
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        
        picker.dismissViewControllerAnimated(true) { () -> Void in
        
        }
    }
    
    //可以编辑的时候
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        chooseView.addimage(image)
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
}

//MARK:--设置textView
extension SinaPublishViewController {
    
    private func setupTextView(){
        
        view.addSubview(textView)
        
        //添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.top.equalTo(view.snp_top)
            make.bottom.equalTo(view.snp_bottom)
        }
        
        //设置占位符
        textView.font = UIFont.systemFontOfSize(14)
        textView.holdText = "分享微博... ..."
        
        //设置代理
        textView.delegate = self
        
        //键盘滑动消失
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        
        //添加选择图片视图
        view.addSubview(chooseView)
        
        chooseView.backgroundColor = UIColor.brownColor()
        
        chooseView.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(textView.snp_left).offset(SinaHomeMargin)
            make.top.equalTo(textView.snp_top).offset(150)
            make.width.equalTo(kUIScreenWidth - 2 * SinaHomeMargin)
            make.height.equalTo(chooseView.snp_width)
        }
    }
    
}

//MARK:--textView 代理方法
extension SinaPublishViewController {
    
    func textViewDidChange(textView: UITextView) {
        
        if textView.hasText() {
            
            //不显示占位符
            self.textView.holdText = ""
        
        }else{
            //显示占位符
            self.textView.holdText = "分享微博... ..."
        }
        //重绘
        self.textView.setNeedsDisplay()
        
        //设置发布按钮点击
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
}



//MARK:--设置导航条
extension SinaPublishViewController {
    
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "publish")
        //默认不可选中
        navigationItem.rightBarButtonItem?.enabled = false
        
        //标题
        let titleView = UILabel()
        //设置lable的frame
        titleView.frame = CGRectMake(0, 0, 200, 44)
        titleView.numberOfLines = 0
        titleView.textAlignment = NSTextAlignment.Center
        
        let str = "发微博\nHan_pngf"
        let attribute = NSMutableAttributedString(string: str)
        let count = 3
        
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(10)], range: NSMakeRange(0, count))
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14),NSForegroundColorAttributeName: UIColor.orangeColor()], range: NSMakeRange(count, str.characters.count - count))
        
        titleView.attributedText = attribute
        
        navigationItem.titleView = titleView
        
    }
    
    //返回按钮方法
    @objc private func dismiss(){
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    //发布按钮方法
    @objc private func publish(){
        
    }
}